package com.blog.servlet;

import com.blog.dao.ArticleDao;
import com.blog.dao.impl.ArticleDaoImpl;
import com.blog.entity.User;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 文章删除Servlet
 */
@WebServlet("/article/delete")
public class ArticleDeleteServlet extends HttpServlet {
    private ArticleDao articleDao = new ArticleDaoImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 1. 获取文章ID
        String idStr = request.getParameter("id");
        if (idStr == null || idStr.isEmpty()) {
            request.setAttribute("errorMsg", "文章ID不能为空！");
            request.getRequestDispatcher("/error.jsp").forward(request, response);
            return;
        }

        // 2. 转换ID并验证权限
        int id;
        try {
            id = Integer.parseInt(idStr);
        } catch (NumberFormatException e) {
            request.setAttribute("errorMsg", "文章ID格式错误！");
            request.getRequestDispatcher("/error.jsp").forward(request, response);
            return;
        }

        // 3. 执行删除操作
        int rows = articleDao.delete(id);

        // 4. 重定向到文章列表（使用重定向防止表单重复提交）
        response.sendRedirect(request.getContextPath() + "/articles");
    }
}